package com.mike.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mike.model.ResponseResult;
import com.mike.model.User;
import com.mike.service.UserService;
import com.mike.util.RestResultGenerator;
import org.springframework.web.bind.annotation.*;

@RestController
public class UserController {

    /**
     * 增加
     * @param id
     * @param param
     * @return
     */
    @RequestMapping(value = "/users/{id}",method = RequestMethod.POST)
    public ResponseResult addUser(@PathVariable("id") String id, @RequestParam(required=false) String param){
        try{
            if(UserService.addUser(param)) {
                return RestResultGenerator.genResult(true,"add success");
            } else {
                return RestResultGenerator.genResult(false,"add fail");
            }
        }catch (Exception e) {
            return RestResultGenerator.genResult(false,e.getMessage());
        }
    }

    /**
     * 删除
     * @param id
     * @param param
     * @return
     */
    @RequestMapping(value = "/users/{id}",method = RequestMethod.DELETE)
    public ResponseResult deleteUser(@PathVariable("id") String id, @RequestParam(required=false) String param){
        try{
            if(UserService.deleteUser(id,param)) {
                return RestResultGenerator.genResult(true,"delete success");
            } else {
                return RestResultGenerator.genResult(false,"delete fail");
            }
        }catch (Exception e) {
            return RestResultGenerator.genResult(false,e.getMessage());
        }
    }

    /**
     * 修改
     * @param id
     * @param param
     * @return
     */
    @RequestMapping(value = "/users/{id}",method = RequestMethod.PUT)
    public ResponseResult updateUser(@PathVariable("id") String id, @RequestParam(required=false) String param){
        try{
            User user = UserService.updateUser(id,param);
            return RestResultGenerator.genResult(user,"update success");
        }catch (Exception e) {
            return RestResultGenerator.genResult(false,e.getMessage());
        }
    }

    /**
     * 查询
     * @param id
     * @param param
     * @return
     */
    @RequestMapping(value = "/users/{id}",method = RequestMethod.GET)
    public ResponseResult getUser( @PathVariable("id") String id,@RequestParam(required=false)  String param){
        try{
            User user = UserService.getUser(id);
            return RestResultGenerator.genResult(user,"get success");
        }catch (Exception e) {
            return RestResultGenerator.genResult(false,e.getMessage());
        }
    }}
